﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAP.Middleware.Connector;
using CM.DL.DALC.NC03;
using DECOR.BL.BE;

namespace DECOR.DL.DALC.NC03
{
    public class CentroDALC : ICentroDALC
    {
        private string _connId = string.Empty;

        public static CentroDALC Instance(string pConnId)
        {
            if (_instance == null)
            {
                lock (typeof(CentroDALC))
                {
                    if (_instance == null)
                    {
                        _instance = new CentroDALC(pConnId);
                    }
                }
            }
            return _instance;
        }
        private CentroDALC(string pConnId) { this._connId = pConnId; }
        private CentroDALC() { }
        private static volatile CentroDALC _instance = null;   
        #region ICentroDALC Members

        /// <summary>
        /// Devuelve una lista de centros de acuerdo al material y a la organización de ventas.
        /// </summary>
        /// <param name="pCodMaterial">Objeto que contiene el código de material.</param>
        /// <param name="pOrgVentas">Código de la organización de ventas.</param>
        public List<DECOR.BL.BE.GenericBE> listar(string pCodMaterial, string pOrgVentas)
        {
            IRfcFunction function = null; RfcDestination dest = null;
            DestConfig dc = new DestConfig();
            List<GenericBE> listaResult = new List<GenericBE>();
            GenericBE obj = null;
            string RESULT =  "";
            try
            {
                dest = DALC.getDestination(out dc);
                function = dest.Repository.CreateFunction("ZWEB_LISTA_CENTROS");
                function.SetValue("P_MATNR", pCodMaterial);
                function.SetValue("P_VKORG", pOrgVentas);
                function.Invoke(dest);

                IRfcTable T001W = function.GetTable("T_T001W");
                RESULT = function.GetString("C_RESULT");

                foreach (IRfcStructure item in T001W)
                {
                    obj = new GenericBE();

                    obj.Codigo = item["WERKS"].GetString();
                    obj.Descripcion = item["WERKS"].GetString() + " :: " + item["NAME1"].GetString();
                    listaResult.Add(obj);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return listaResult;
        }

        #endregion
    }
}
